import { createRouter, createWebHistory } from 'vue-router'
import { Store } from '@/store/index'


import api from '@/axios/index'
// 页面组件懒加载
const Index = () => import('../views/Index.vue')
const Home = () => import('../views/system/Home.vue')
const Login = () => import('../views/Login.vue')
const Register = () => import('../views/Register.vue')
const routes = [
    {
        path: '/',
        name: 'Index',
        component: Index,
        children: [
            {
                path: '/Home',
                name: '系统首页',
                meta: { title: '系统首页' },
                component: Home,
            },

        ]
    },
    {
        path: '/Login',
        name: 'login',
        component: Login,
    },
    {
        path: '/Register',
        name: 'register',
        component: Register,
    },
]

const router = createRouter({
    history: createWebHistory(process.env.BASE_URL),
    routes
})

router.beforeEach(async (to, from, next) => {
    // console.log(to.path)
    // console.log(to.component)
    const store = Store()
    const user = localStorage.getItem('CurUser')
    const indexRoute = routes.find(route => route.name === 'Index')
    if (indexRoute.children.length == 1)
        store.hasRoutes = false
    if (!user) {
        console.log('未登录')
        if (to.path === '/Login' || to.path === '/Register')
            next()
        else
            next('/Login')
    } else if (user && !store.hasRoutes) {
        console.log('已登录')
        const menu = await loadMenu(JSON.parse(user));
        addRoutes(menu)
        store.hasRoutes = true

        next({ ...to, replace: true })
    } else
        console.log('放行')
    next()
})

async function loadMenu(user) {
    const config = {
        headers: {
            "Content-Type": "application/json"
        }
    };

    try {
        const res = await api.post("/menu/nav", user, config);
        const menuList = res.data.navs;
        const permList = res.data.perm;
        const store = Store()
        // 将菜单列表和权限列表保存到Store中
        store.setMenuList(menuList);
        store.setPermList(permList);

        // console.log(menuList);
        return menuList; // 返回 menuList
    } catch (error) {
        console.error("加载菜单失败:", error);
        return []; // 出错时返回空数组
    }
}



function addRoutes(menuList) {
    let indexRoute = routes.find(item => item.path === '/')
    // console.log(indexRoute);
    menuList.forEach(menu => {
        if (menu.type != 0) {
            let childRoute = {
                path: "/" + menu.path,
                name: menu.name,
                meta: { title: menu.name },
                component: () => import(`@/views/${menu.component}`)
            }
            indexRoute.children.push(childRoute)
        }
        if (menu.children) {
            menu.children.forEach(child => {
                let childRoute = {
                    path: "/" + child.path,
                    name: child.name,
                    meta: { title: child.name },
                    component: () => import(`@/views/${child.component}`)
                }
                indexRoute.children.push(childRoute)
            })
        }
    })
    // console.log(indexRoute)
    router.addRoute(indexRoute)
}
// 避免 Vue Router 3.6+ 的 NavigationDuplicated 错误
const originalPush = router.push
router.push = function push(location) {
    return originalPush.call(this, location).catch(err => err)
}

const originalReplace = router.replace
router.replace = function replace(location) {
    return originalReplace.call(this, location).catch(err => err)
}
export default router